import Vue from 'vue'
import VueRouter from 'vue-router'
// import Home from '../views/Home.vue'
import { getToken } from '../utils/storage'
Vue.use(VueRouter)

const routes = [{
        path: '/',
        name: 'Layout',
        redirect: '/article',
        component: () =>
            import ('../views/Layout.vue'),
        children: [{
            path: '/article',
            name: 'Article',
            component: () =>
                import ('../views/Article.vue')
        }, {
            path: '/collect',
            name: 'Collect',
            component: () =>
                import ('../views/Collect.vue')
        }, {
            path: '/like',
            name: 'Like',
            component: () =>
                import ('../views/Like.vue')
        }, {
            path: '/my',
            name: 'My',
            component: () =>
                import ('../views/My.vue')
        }, ]
    }, {
        path: '/login',
        name: 'Login',
        component: () =>
            import ('../views/Login.vue')
    }, {
        path: '/register',
        name: 'Register',
        component: () =>
            import ('../views/Register.vue')
    }, {
        path: '/detail',
        name: 'Detail',
        component: () =>
            import ('../views/Detail.vue')
    },
    // {
    //   path: '/about',
    //   name: 'About',
    //   // route level code-splitting
    //   // this generates a separate chunk (about.[hash].js) for this route
    //   // which is lazy-loaded when the route is visited.
    //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
    // }
]

const router = new VueRouter({
    routes
})

//全局前置守卫：
// -- // 1. 所有的路由一旦被匹配到，在真正渲染解析之前，都会先经过全局前置守卫
// -- // 2. 只有全局前置守卫放行，才能看到真正的页面
//这个 面经移动端 项目，只对 登录用户 开放，如果未登录，一律拦截到登录
//只有登录和注册页不需要token,其他的均需要
const whiteList = ['/login', '/register']
router.beforeEach((to, from, next) => {
    const token = getToken()
        // 如果有token，直接放行
    if (token) {
        next() //放行
    } else {
        if (whiteList.includes(to.path)) {
            next()
        } else {
            next('/login') //拦截到登录页
        }
    }
})

export default router